#!/usr/bin/env bash
set -euo pipefail

# 仅停止 FastAPI（不影响 Docker 依赖）

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PID_FILE="${ROOT_DIR}/uvicorn.pid"

stop_api() {
    if [[ ! -f "${PID_FILE}" ]]; then
        echo "[api] 未找到 PID 文件，可能未启动"
        return
    fi

    pid="$(cat "${PID_FILE}")"
    if ! kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[api] PID ${pid} 不存在，清理残留 PID 文件"
        rm -f "${PID_FILE}"
        return
    fi

    echo "[api] 停止 FastAPI (pid ${pid}) ..."
    kill "${pid}" || true
    for _ in {1..10}; do
        if kill -0 "${pid}" >/dev/null 2>&1; then
            sleep 1
        else
            break
        fi
    done

    if kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[api] 进程未退出，发送 SIGKILL"
        kill -9 "${pid}" || true
    fi

    rm -f "${PID_FILE}"
    echo "[api] 已停止"
}

stop_api "$@"
